<?php

namespace Common\Widget;

use Common\Controller\WidgetController;

class FormWidget extends WidgetController
{
    // 资源包
    protected $src = [
        // elUI
        'ElementUI' => ['<css file="__PUBLIC__/element-ui/lib/theme-chalk/index.css" />', '<js file="__PUBLIC__/js/vue.min.js" />', '<js file="__PUBLIC__/element-ui/lib/index.js" />'],
        // vue开发环境
        'vue' => '<js file="__JS__/vue.min.js" />',
        // 富文本编辑器
        'ueditor' => ['<js file="__JS__/UEditor/ueditor.config.js" />', '<js file="__JS__/UEditor/ueditor.all.js" />'],
        // 图片剪切
        'cropperjs' => ['<css file="__PUBLIC__/cropperjs/cropper.min.css" />', '<js file="__PUBLIC__/cropperjs/cropper.min.js" />', '<js file="__PUBLIC__/jquery-cropper/jquery-cropper.min.js" />',],
    ];

    public function input($param)
    {
        $this->assign($param);
        $this->display('input');
    }

    public function _empty($method, $param)
    {
        $param = $param[0];
        $param['type'] = $method;
        $this->input($param);
    }

    public function editor($param)
    {
        $this->assets($this->src['ueditor']);
        // 默认配置
        $opt = array(
            'zIndex' => 0,
            'serverUrl' => main_url('Api/Upload/UEditorController', array('PHPSESSIONID' => session_id())),
            'UEDITOR_HOME_URL' => C('TMPL_PARSE_STRING.__JS__') . '/UEditor/',
            'initialFrameWidth' => '100%',
            'wordCount'=>false,
            'codeMirrorJsUrl' => C('TMPL_PARSE_STRING.__JS__') . '/UEditor/third-party/codemirror/codemirror.js',
            'codeMirrorCssUrl' => C('TMPL_PARSE_STRING.__JS__') . '/UEditor/third-party/codemirror/codemirror.css',
            'highlightJsUrl' => C('TMPL_PARSE_STRING.__JS__') . '/UEditor/third-party/SyntaxHighlighter/shCore.js',
            'highlightCssUrl' => C('TMPL_PARSE_STRING.__JS__') . '/UEditor/third-party/SyntaxHighlighter/shCoreDefault.css',
        );
        !$param['id'] && $param['id'] = $param['name'];
        !$param['tool'] && $param['tool'] = 'full';
        $toolList = array(
            // 简单工具 一般给网站用户使用
            'simple' => [[
                'undo', //撤销
                'redo', //重做
                'bold', //加粗
                'indent', //首行缩进
                'italic', //斜体
                'underline', //下划线
                'strikethrough', //删除线
                'subscript', //下标
                'superscript', //上标
                'formatmatch', //格式刷
                'horizontal', //分隔线
                'removeformat', //清除格式
                'fontfamily', //字体
                'fontsize', //字号
                'simpleupload', //单图上传
                'justifyleft', //居左对齐
                'justifyright', //居右对齐
                'justifycenter', //居中对齐
                'justifyjustify', //两端对齐
                'forecolor', //字体颜色
                'backcolor', //背景色
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                'background', //背景
                'anchor', //锚点
                'link', //超链接
                'emotion', //表情
                'fullscreen', //全屏
            ]],
            // 游客编辑器 一般个游客使用
            'guest' => [[
                'undo', //撤销
                'redo', //重做
                'bold', //加粗
                'indent', //首行缩进
                'italic', //斜体
                'underline', //下划线
                'strikethrough', //删除线
                'subscript', //下标
                'superscript', //上标
                'formatmatch', //格式刷
                'horizontal', //分隔线
                'removeformat', //清除格式
                'fontfamily', //字体
                'fontsize', //字号
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                'link', //超链接
                'emotion', //表情
                'fullscreen', //全屏
            ]],
            // 全部工具 一般给管理员使用
            'full' => [[
                'anchor', //锚点
                'undo', //撤销
                'redo', //重做
                'bold', //加粗
                'indent', //首行缩进
                'snapscreen', //截图
                'italic', //斜体
                'underline', //下划线
                'strikethrough', //删除线
                'subscript', //下标
                'fontborder', //字符边框
                'superscript', //上标
                'formatmatch', //格式刷
                'source', //源代码
                'blockquote', //引用
                'pasteplain', //纯文本粘贴模式
                'selectall', //全选
                'print', //打印
                'preview', //预览
                'horizontal', //分隔线
                'removeformat', //清除格式
                'time', //时间
                'date', //日期
                'unlink', //取消链接
                'insertrow', //前插入行
                'insertcol', //前插入列
                'mergeright', //右合并单元格
                'mergedown', //下合并单元格
                'deleterow', //删除行
                'deletecol', //删除列
                'splittorows', //拆分成行
                'splittocols', //拆分成列
                'splittocells', //完全拆分单元格
                'deletecaption', //删除表格标题
                'inserttitle', //插入标题
                'mergecells', //合并多个单元格
                'deletetable', //删除表格
                'cleardoc', //清空文档
                'insertparagraphbeforetable', //"表格前插入行"
                'insertcode', //代码语言
                'fontfamily', //字体
                'fontsize', //字号
                'paragraph', //段落格式
                'simpleupload', //单图上传
                'insertimage', //多图上传
                'edittable', //表格属性
                'edittd', //单元格属性
                'link', //超链接
                'emotion', //表情
                'spechars', //特殊字符
                'searchreplace', //查询替换
                'map', //Baidu地图
                'gmap', //Google地图
                'insertvideo', //视频
                'help', //帮助
                'justifyleft', //居左对齐
                'justifyright', //居右对齐
                'justifycenter', //居中对齐
                'justifyjustify', //两端对齐
                'forecolor', //字体颜色
                'backcolor', //背景色
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                'fullscreen', //全屏
                'directionalityltr', //从左向右输入
                'directionalityrtl', //从右向左输入
                'rowspacingtop', //段前距
                'rowspacingbottom', //段后距
                'pagebreak', //分页
                'insertframe', //插入Iframe
                'imagenone', //默认
                'imageleft', //左浮动
                'imageright', //右浮动
                'attachment', //附件
                'imagecenter', //居中
                'wordimage', //图片转存
                'lineheight', //行间距
                'edittip ', //编辑提示
                'customstyle', //自定义标题
                'autotypeset', //自动排版
                'webapp', //百度应用
                'touppercase', //字母大写
                'tolowercase', //字母小写
                'background', //背景
                'template', //模板
                'scrawl', //涂鸦
                'music', //音乐
                'inserttable', //插入表格
                'drafts', // 从草稿箱加载
                'charts', // 图表
            ]]
        );// 编辑器工具
        $param['option'] = array_merge($opt, $param['option'] ?: array());
        if ($param['tool'] != 'full') {
            $param['option']['toolbars'] = $toolList[$param['tool']];
        }
        $this->assign($param);
        $this->display('editor');
    }

    public function radio($param)
    {
        $this->assign($param);
        $this->display('radio');
    }

    public function checkbox($param)
    {
        if (!is_array($param['value'])) {
            $param['value'] = array_filter(preg_split('/[\r\n|,]+/', $param['value']));
        }
        $this->assign($param);
        $this->display('checkbox');
    }

    public function select($param)
    {
        $this->assign($param);
        $this->display('select');
    }

    public function uploader($param)
    {
        $this->assets($this->src['ElementUI']);
        if (!$param['name']) {
            echo "请设置name属性";
            return false;
        }
        $param['id'] || $param['id'] = $param['name'];
        if (!$param['list']) {
            $ids = $this->parseIds($param['value']);
            if ($ids) {
                $model = D('Common/File');
                $param['list'] = $model->where(['id' => ['in', $ids]])->select();
                $ids = [];
                foreach ($param['list'] as &$row) {
                    $row['url'] = $row['download_url'];
                    $ids[] = $row['id'];
                }
                $param['value'] = implode(',', $ids);
            }
            if (!$param['list']) $param['list'] = [];
        }
        $param['from'] || $param['from'] = 'system';
        $param['api'] || $param['api'] = main_url('Api/upload/FileUpload', ['from' => $param['from'], 'ajax' => 'ajax']);
        $user_option = $param['option'];
        $default_option = [
            'name' => $param['name'],
            'action' => $param['api'],
            'class' => 'upload',
            ':on-preview' => 'handlePreview',
            ':on-remove' => 'handleRemove',
            ':before-remove' => 'beforeRemove',
            ':on-success' => 'handleSuccess',
            ':on-error' => 'handleError',
            ':on-change' => 'handleChange',
            ':on-exceed' => 'handleExceed',
            ':file-list' => 'fileList',
            ':auto-upload' => 'false',
            'limit' => '3',
            'multiple' => '',
        ];
        if (is_array($param['option'])) {
            $param['option'] = array_merge($default_option, $param['option']);
        } else {
            $param['option'] = $default_option;
        }
        $this->assign($param);
        if (!$param['container_tpl']) {
            switch ($param['option']['list-type']) {
                case 'text':
                    $param['container_tpl'] = $this->fetch($this->getTmpl('uploader-text-tpl'));
                    break;
                case 'picture':
                    $param['container_tpl'] = $this->fetch($this->getTmpl('uploader-picture-tpl'));
                    break;
                case 'picture-card':
//                    if (!$user_option[':on-preview']) $param['option'][':on-preview'] = 'handlePictureCardPreview';
//                    $this->assign($param);
                    $param['container_tpl'] = $this->fetch($this->getTmpl('uploader-picture-card-tpl'));
                    break;
            }
        }
        $this->assign($param);
        $this->display('uploader');
    }

    protected function parseIds($v)
    {
        $ex = explode(',', $v);
        $ids = [];
        foreach ($ex as $r) {
            if (is_numeric($r)) {
                $ids[] = $r;
            }
        }
        return $ids;
    }

    public function picture($param)
    {
        $param['option']['list-type'] = 'picture';
        $this->uploader($param);
    }


    public function img_crop($param)
    {
        $this->assets(array_merge($this->src['ElementUI'], $this->src['cropperjs']));
        if (!$param['name']) {
            echo "请设置name属性";
            return false;
        }
        $param['id'] || $param['id'] = $param['name'];
        $param['limit'] || $param['limit'] = 3;
        $param['value'] || $param['value'] = [];
        $param['list'] || $param['list'] = [];
        // 处理默认值
        if (!is_array($param['value'])) {
            $json = json_decode($param['value'], true);
            if ($json || is_array($json)) {
                $param['value'] = $json;
            } else {
                $tmp = $param['value'];
                $param['value'] = [];
                $param['value'][] = $tmp;
            }
        }
        // 预览列表
        if (!$param['list']) {
            $list = D('Common','Logic')->crop_format($param['value']);
            $param['list'] = is_array($list)?$list:[$list];
        }else if (!is_array($param['list'])) {
            $json = json_decode($param['list'], true);
            if ($json || is_array($json)) {
                $param['list'] = $json;
            } else {
                $tmp = $param['list'];
                $param['list'] = [];
                $param['list'][] = $tmp;
            }
        }
        $def_opt = [
            'aspectRatio' => 16 / 9,
            'preview' => '.img_preview',
            'viewMode' => 1,
            'dragCrop' => false,
            'dragMode' => 'move',
            'autoCropArea' => 0.988,
        ];
        if ($param['width'] && $param['height'] && !$param['option']['aspectRatio']) {
            $param['option']['width'] = $param['width'];
            $param['option']['height'] = $param['height'];
            $param['option']['aspectRatio'] = intval($param['width']) / intval($param['height']); // 自动计算选区比例
        } else if ($param['option']['width'] && $param['option']['height'] && !$param['option']['aspectRatio']) {
            $param['option']['aspectRatio'] = intval($param['option']['width']) / intval($param['option']['height']); // 自动计算选区比例
        }
        $param['option'] || $param['option'] = [];
        $param['option'] = array_merge($def_opt, $param['option']);
        $this->assign($param);
        $this->display('img_crop');
    }
}
